var sattr=function(n,v){if(v==undefined){ let session =req.getSession(false);
	return (session != null ?session.getAttribute(v) : null);}else{session.setAttribute(n,v)}}
function index(tbl){
	var ua = req.getHeader("user-agent").toLowerCase();
	if (ua.indexOf("qq/") > 0){
		print("是qq")
		attr("_httpurl","login/qq")
		$sess(tbl.sid).setAttribute("qrcodegoto","login/qq");
		return null;
	}else if(ua.indexOf("micromessenger")>0){
		print("iswx"+tbl)
		attr("_httpurl","http://m.iepsy.com/")
		$sess(tbl.sid).setAttribute("qrcodegoto","https://open.weixin.qq.com/connect/qrconnect?appid=wxe86dd9c3d7581239&redirect_uri=http%3A%2F%2Fwww.iepsy.com%2Flogin%2Fwx&response_type=code&scope=snsapi_login#wechat_redirect");
		return null;
	}else{
		attr("_httpurl","m/login")
		return null;
	}
	return "";
}

//验证码
function gotourl(tbl){
	if(tbl.remove=="yes"){
		 session.setAttribute("qrcodegoto",null)
	}
	return sattr("qrcodegoto");
}
function qq(tbl){
	//获取Access Token
	
	var gotourl="users/";
	var ua = req.getHeader("user-agent").toLowerCase();
	if (ua.indexOf("qq/") > 0){
		gotourl="m/";
	}else if(ua.indexOf("micromessenger")>0){
		gotourl="m/";
	}else{
		
	}
	if(sattr("goto")!=null){
		gotourl=sattr("goto");
	}
	if(tbl.code==undefined){
		var url="https://graph.qq.com/oauth2.0/authorize?redirect_uri=http%3A%2F%2Fwww.iepsy.com%2Flogin%2Fqq&client_id=101287138&state=1&response_type=code";
		resp.sendRedirect(url);
	}else{
	try {
		var url="https://graph.qq.com/oauth2.0/token?redirect_uri=http%3A%2F%2Fwww.iepsy.com%2Flogin%2Fqq&grant_type=authorization_code&client_id=101287138&client_secret=283caabc4027419fd832397d53125f8d&code="+tbl.code;
		var access_token=Http.get(url).getContent().split("&")[0].split("=")[1]
		//print(access_token)
			//获取openid
		var urlopenid="https://graph.qq.com/oauth2.0/me?access_token="+access_token;
		
		var qqrt=foJson(Http.get(urlopenid).getContent().replace("callback(","").replace(")",""));
		var openid=qqrt.openid;
		
		var user=dao.fetch("users",Cnd.where("qqid","=",openid))
		if(user==null){
		var url_user="https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=101287138&openid="+openid;
		var qquser=foJson(Http.get(url_user).getContent());
		var u=new Record();
		u.put("img",ImageUtil.save(qquser.figureurl_qq_2))
		u.put("nickname",qquser.nickname)
		u.put("sex",qquser.gender)
		u.put("area1",qquser.province)
		u.put("area2",qquser.city)
		u.put("username","qq"+openid)
		u.put("password","123456")
		u.put("qqid",openid)
		u.put("reg_time",new java.util.Date())
		u.put("reg_ip",req.getRemoteAddr())
		u.put("login_ip",req.getRemoteAddr())
		u.put(".table","users");
		$save(u)
		user=dao.fetch("users",Cnd.where("qqid","=",openid))
		sattr("user",user)
		attr("_httpurl",gotourl)
		
		addCookie("user",URLEncoder.encode(user,"UTF-8"));
		return u;
		}else{
			sattr("user",user)
		addCookie("user",URLEncoder.encode(user,"UTF-8"));
			attr("_httpurl",gotourl)
		}
	} catch (e) {
		print(e)
	}
	}
	return null;
}
function sina(tbl){
	var gotourl="users/";
	if(sattr("goto")!=null){
		gotourl=sattr("goto");
	}
	if(tbl.code==undefined){
	var url="https://api.weibo.com/oauth2/authorize?client_id=3548294181&response_type=code&redirect_uri=http://www.iepsy.com/login/sina"
		 resp.sendRedirect(url);
	}else{
		var url1="https://api.weibo.com/oauth2/access_token";
		var map=new HashMap();
		map.put("client_id","3548294181")
		map.put("client_secret","fb82f3a1a94ff175233b9c02d4227881")
		map.put("grant_type","authorization_code")
		map.put("redirect_uri","http://www.iepsy.com/login/sina")
		map.put("code",tbl.code)
		var txt=Http.post(url1,map);
		var wbs=foJson(txt);
		var access_token=wbs.access_token;
		var uid=wbs.uid;
		var url2="https://api.weibo.com/2/users/show.json?access_token="+access_token+"&uid="+uid;
		
		var user=dao.fetch("users",Cnd.where("wbid","=",uid))
		if(user==null){
			var wbrt=Http.get(url2);
			print("............-------------------"+access_token)
		var weibo=foJson(wbrt);
		print("............-------------------"+weibo)
		var u=new Record();
		var img=down99(weibo.avatar_large,"d:/tomcat/webapps/upload/image/"+Times.format("yyyyMMdd",new java.util.Date())+"/"+uuid()+".jpg")
		u.put("img",img)
		u.put("nickname",weibo.name)
		if(weibo.gender=="m"){
			u.put("sex","男")
		}else if(weibo.gender=="f"){
			u.put("sex","女")
		}else{
			u.put("sex","保密")
		}
		u.put("addr",weibo.location)
		u.put("username","weibo"+uid)
		u.put("password","123456")
		u.put("wbid",uid)
		u.put("reg_time",new java.util.Date())
		u.put("reg_ip",req.getRemoteAddr())
		u.put("login_ip",req.getRemoteAddr())
		u.put(".table","users");
		$save(u)
		var us=dao.fetch("users",Cnd.where("wbid","=",uid));
		sattr("user",us)
		attr("_httpurl",gotourl)
		user=us;
		try {
			addCookie("user",user);
		} catch (e) {
			// TODO: handle exception
		}
		
		}else{
			sattr("user",user)
		try {
			addCookie("user",user);
		} catch (e) {
			// TODO: handle exception
		}
			attr("_httpurl",gotourl)
		}
	}
		
}
function baidu(tbl){
	var gotourl="users/";
	if(sattr("goto")!=null){
		gotourl=sattr("goto");
	}
	if(tbl.code==undefined){
		var store = new BaiduCookieStore("CSlvQ3vMGOXImWxh19XHsrlv", req, resp);
	    var baidu = null;
	    try {
	        baidu = new Baidu("CSlvQ3vMGOXImWxh19XHsrlv", "Bwknmxif4vsj90ZwMZ3teNTnRxKhlMor", "http://www.iepsy.com/login/baidu", store, req);
	        var state = baidu.getState();
	        var params = new HashMap();
	        params.put("state", state);
	        var authorizeUrl = baidu.getBaiduOAuth2Service().getAuthorizeUrl(params);
	        resp.sendRedirect(authorizeUrl);
	    } catch (e) {
	        log.debug("BaiduOAuthException ", e);
	    }
		}else{
			var store = new BaiduCookieStore("CSlvQ3vMGOXImWxh19XHsrlv", req, resp);
		    var baidu = null;
		        try {
		        	baidu = new Baidu("CSlvQ3vMGOXImWxh19XHsrlv", "Bwknmxif4vsj90ZwMZ3teNTnRxKhlMor", "http://www.iepsy.com/login/baidu", store, req);
		            /*accessToken = baidu.getAccessToken();
		            refreshToken = baidu.getRefreshToken();
		            sessionKey = baidu.getSessionKey();
		            sessionSecret = baidu.getSessionSecret();*/
		        	var buser = baidu.getLoggedInUser();
		        	var u0=dao.fetch("users",Cnd.where("bd_id","=",buser.getUid()));
		        	if(u0==null){
		            
		            var u=new Record();
		            	u.put("img",ImageUtil.save("http://himg.bdimg.com/sys/portrait/item/"+buser.getPortrait()+".jpg"))
		    		u.put("nickname",buser.getUname())
		    		u.put("username","baidu"+buser.getUid())
		    		u.put("password","123456")
		    		u.put("bd_id",buser.getUid()+"")
		    		u.put("reg_time",new java.util.Date())
		    		u.put("reg_ip",req.getRemoteAddr())
		    		u.put("login_ip",req.getRemoteAddr())
		    		u.put(".table","users");
		    		$save(u)
		    		u0=dao.fetch("users",Cnd.where("baidu_id","=",buser.getUid()));
		        	}
		    		sattr("user",u0);
		    		var user=u0;
		    		addCookie("user",URLEncoder.encode(user,"UTF-8"));
		    		attr("_httpurl",gotourl)
		            return buser;
		        } catch (e) {
		            print(e)
		        }
		}
}
function wx(tbl){
	var gourl="users/";
	if(sattr("goto")!=null){
		gourl=sattr("goto");
	}
	if(tbl.code==undefined) {// 是微信浏览器
		  attr("_httpurl","http://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe86dd9c3d7581239&redirect_uri=http%3a%2f%2fwww.iepsy.com%2flogin%2fwx&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect")
		  return null;
	}
	if(tbl.code!=undefined){
		var wx_user=com.jse.util.Jssdk.getUser(tbl.code)
		log.error(wx_user)
		let unionid=wx_user.unionid;
		let openid=wx_user.openid;
		var nickname=wx_user.nickname;
		try {
			nickname=nickname.replaceAll("[\\x{10000}-\\x{10FFFF}]", "");
		} catch (e) {
			
		}
		var sex=wx_user.sex=="1"?"男":"女";
		var city=wx_user.city;
		var province= wx_user.province;
		var country= wx_user.country;
		let u1=dao.fetch("users",Cnd.where("unionid","=",unionid))
		if(u1==null){
			u1=dao.fetch("users",Cnd.where("openid","=",openid))
		}
		if(u1==null){
		var u=new Record();
		var img=down99(wx_user.headimgurl,"d:/tomcat/webapps/upload/image/"+Times.format("yyyyMMdd",new java.util.Date())+"/"+uuid()+".jpg")
		u.put("nickname",nickname)
		u.put("img",img)
		u.put("username","wx"+openid)
		u.put("password","123456")
		u.put("openid",openid)
		u.put("unionid",unionid)
		u.put("reg_time",new java.util.Date())
		u.put("reg_ip",req.getRemoteAddr())
		u.put("login_ip",req.getRemoteAddr())
		u.put(".table","users");
		$save(u)
		sattr("user",dao.fetch("users",Cnd.where("openid","=",openid)))
		
		
		}else{
				
			var img=down99(wx_user.headimgurl,"d:/tomcat/webapps/upload/image/"+Times.format("yyyyMMdd",new java.util.Date())+"/"+uuid()+".jpg")
				var chain=Chain.make("nickname",nickname)
				chain.put("sex",sex)
				chain.put("province",province)
				chain.put("city",city)
				chain.put("country",country)
				chain.put("img",img);
				if(isEmpty(u1.openid)){
					chain.put("openid",openid)
				}
				if(isEmpty(u1.unionid)){
					chain.put("unionid",unionid)
				}
				dao.update("users",chain,Cnd.where("id","=",u1.id))
				sattr("user",dao.fetch("users",Cnd.where("id","=",u1.id)))
				print(user())
		}
		sattr("goto",null);
	}
	
	return ">>:"+gourl;
}
function down99(urlstr,filePath){
	var url = new java.net.URL(urlstr);
	// 打开链接
	var conn = url.openConnection();
	// 设置请求方式为"GET"
	conn.setRequestMethod("GET");
	// 超时响应时间为5秒
	conn.setConnectTimeout(5 * 1000);
	// 通过输入流获取图片数据
	var inStream = conn.getInputStream();
	// 得到图片的二进制数据，以二进制封装得到数据，具有通用性
	var data = Http.readInputStream(inStream);
	var imageFile = new java.io.File(filePath);
	var fileParent = imageFile.getParentFile();  
	if(!fileParent.exists()) {
		fileParent.mkdirs();
	}
	var outStream = new java.io.FileOutputStream(imageFile);
	// 写入数据
	outStream.write(data);
	// 关闭输出流
	outStream.close();
	return filePath.replace("d:/tomcat/webapps/","");
}
